package com.party.mobile.biz.analysis;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.party.common.utils.HttpServletRequestUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.analysis.StatisticsPageFlow;
import com.party.core.model.member.MemberGroup;
import com.party.core.service.analysis.IStatisticsPageFlowService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.utils.MyBeanUtils;
import com.party.mobile.web.dto.analysis.PageFlowInput;
import com.party.mobile.web.dto.analysis.PageLoadTimeInput;
import nl.bitwalker.useragentutils.UserAgent;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * 流程业务处理
 *
 * @author yifeng
 * @date 2018/8/8 0008
 * @time 下午 19:48
 */
@Service
public class StatisticsFlowBizService {
    @Autowired
    private IStatisticsPageFlowService statisticsPageFlowService;
    @Autowired
    private StatisticsUserBizService statisticsUserBizService;
    @Autowired
    private IMemberGroupService memberGroupService;

    public final String pageRedisKey = "page_unique_code";

    public final String eventRedisKey = "event_unique_code";

    public final String userIdRedisKey = "user_unique_code";

    /**
     * 进入页面时，保存记录
     *
     * @param flowInput 输入参数
     * @param request   request
     * @return
     */
    public String insertPageFlow(PageFlowInput flowInput, HttpServletRequest request) throws Exception {
        StatisticsPageFlow pageFlow = new StatisticsPageFlow();

        String loadTime = flowInput.getLoadTime();
        if (StringUtils.isNotEmpty(loadTime)) {
            PageLoadTimeInput loadTimeObj = JSONObject.parseObject(loadTime, PageLoadTimeInput.class);
            if (loadTimeObj != null) {
                MyBeanUtils.copyBeanNotNull2Bean(loadTimeObj, pageFlow);
            }
        }

        String htmlUrl = flowInput.getHtmlUrl();
        if (StringUtils.isNotEmpty(htmlUrl)) {
            if (htmlUrl.contains("?r=")) {
                htmlUrl = htmlUrl.substring(0, htmlUrl.indexOf("?r="));
            } else if (htmlUrl.contains("&r=")) {
                htmlUrl = htmlUrl.substring(0, htmlUrl.indexOf("&r="));
            }
        }
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        // 合作商
        pageFlow.setPartnerId(flowInput.getPartnerId());
        // 页面名称
        pageFlow.setName(flowInput.getName());
        // 页面路径
        pageFlow.setUrl(htmlUrl);
        // 浏览器
        pageFlow.setBrower(userAgent.getBrowser().toString());
        // 操作系统
        pageFlow.setOs(userAgent.getOperatingSystem().toString());
        // ip
        String ip = HttpServletRequestUtils.getRemoteIpAddress(request);
        pageFlow.setIp(ip);
        // 运营商
        // String operator = HttpServletRequestUtils.getAddresses(ip);
        // pageFlow.setOperator(operator);
        // 用户编号
        pageFlow.setUserId(flowInput.getUserId());
        // 分辨率
        pageFlow.setDpi(flowInput.getDpi());
        // 唯一码
        pageFlow.setUniqueCode(flowInput.getUniqueCode());
        /**
         * lastHtmlUrl不为空，说明不是第一个页面，找到直属父级对象。
         */
        if (StringUtils.isNotEmpty(flowInput.getParentId())) {
            pageFlow.setIsStart(YesNoStatus.NO.getCode());
            pageFlow.setParentId(flowInput.getParentId());
        } else {
            pageFlow.setIsStart(YesNoStatus.YES.getCode());
            pageFlow.setIsEnd(YesNoStatus.NO.getCode());
        }
        return statisticsPageFlowService.insert(pageFlow);
    }

    /**
     * 离开页面时，更新停留时长
     *
     * @param flowInput 输入参数
     */
    public void updatePageStayTime(PageFlowInput flowInput, HttpServletRequest request) throws Exception {
        StatisticsPageFlow pageFlow = statisticsPageFlowService.get(flowInput.getFlowId());
        if (pageFlow != null) {
            pageFlow.setStayTime(flowInput.getStayTime());
            statisticsPageFlowService.update(pageFlow);
        }
    }

    /**
     * 从cookie里面获取用户唯一码
     *
     * @param request
     * @return
     */
    public String getCookieUserId(HttpServletRequest request) {
        String userId = null;
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(userIdRedisKey)) {
                    userId = cookie.getValue();
                    break;
                }
            }
        }
        return userId;
    }

    /**
     * 从cookie里面获取唯一码
     *
     * @param request
     * @return
     */
    public String getCookieUniqueCode(HttpServletRequest request, String key) {
        String uniqueCode = null;
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(key)) {
                    uniqueCode = cookie.getValue();
                    break;
                }
            }
        }
        return uniqueCode;
    }

    /**
     * 生成唯一码
     * 把用户编号，当前页面路径，加时间戳，加随机数，md5加密，加密后的字母转成数字，倒序取18位
     *
     * @param htmlUrl 当前页面路径
     * @param userId  用户编号
     * @return
     */
    public String getUniqueCode(String htmlUrl, String userId) {
        StringBuilder sb = new StringBuilder();
        sb.append(htmlUrl);
        sb.append(userId);
        sb.append(new Random().nextInt(99999));
        sb.append(System.currentTimeMillis());
        String encodeStr = DigestUtils.md5Hex(sb.toString() + "txz123");
        List<String> strings = Lists.newArrayList();
        for (int i = 0; i < encodeStr.length(); i++) {
            char c = encodeStr.charAt(i);
            if (!Character.isDigit(c)) {
                int tempNum = (int) c;
                strings.add(tempNum + "");
            } else {
                strings.add(c + "");
            }
        }
        Collections.reverse(strings);
        String newStr = StringUtils.join(strings.toArray(), "");
        String uniqueCode = newStr.substring(0, 18);
        return uniqueCode;
    }

    /**
     * 进入页面时，更新机构id
     *
     * @param flowInput
     */
    public void updatePagePartnerId(PageFlowInput flowInput) {
        StatisticsPageFlow pageFlow = statisticsPageFlowService.get(flowInput.getFlowId());
        if (pageFlow != null) {
            MemberGroup partner = memberGroupService.get(flowInput.getPartnerId());
            if (null != partner) {
                pageFlow.setPartnerId(flowInput.getPartnerId());
                pageFlow.setPartnerName(partner.getRealname());
                statisticsPageFlowService.update(pageFlow);
            }
        }
    }
}
